package parts4.lesson54;

public class BinaryTree {


    private class Node{
        //因为必须是Comparable的子类，而且需要判断大小
        private Comparable data;
        private Node left;
        private Node right;
        public Node(Comparable data){
            this.data=data;
        }
        public void addNode(Node newNode){
            if(this.data.compareTo(newNode.data)>0){
                if(this.left==null){
                    this.left=newNode;
                }else{
                    this.left.addNode(newNode);
                }
            }else{
                if(this.right==null){
                    this.right=newNode;
                }else{
                    this.right.addNode(newNode);
                }
            }
        }
        public void toArrayNode(){
            if(this.left!=null){
                this.left.toArrayNode();
            }
            BinaryTree.this.resData[BinaryTree.this.foot++]=this.data;
            if(this.right!=null){
                this.right.toArrayNode();
            }
        }
    }
    //根
    private Node root;
    //保存的个数
    private int count;
    private int foot=0;
    private Object[] resData;
    public Object [] toArray(){
        this.foot=0;
        this.resData=new Object[this.count];
        this.root.toArrayNode();
        return this.resData;
    }
    //可以添加任何数据
    public void add (Object data){
        if (data==null){
            return;
        }
        //进行强转
        Node newNode= new Node((Comparable) data);
        if(this.root==null){
            this.root=newNode;
        }else{
            this.root.addNode(newNode);
        }
        this.count++;

    }

}
